package com.fjnu.controller;

import com.fjnu.common.ResponseResult;
import com.fjnu.dto.UserConditionDto;
import com.fjnu.entity.User;
import com.fjnu.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 用户管理控制器
 */
@RestController
@RequestMapping("/blog-api/v0.1/user")
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 根据用户的查询条件来查询用户列表
     * POST: /blog-api/v0.1/user/list
     */
    @PostMapping("/list")
    public ResponseResult<List<User>> list(@RequestBody UserConditionDto userCond) {
        try {
            // 这里简单实现分页查询所有用户，实际可根据userCond条件查询
            List<User> users = userService.queryUsers(userCond, 1, 10).getData();
            return ResponseResult.success(users);
        } catch (Exception e) {
            return ResponseResult.error("查询用户列表失败: " + e.getMessage());
        }
    }

    /**
     * 新增用户
     * POST: /blog-api/v0.1/user/add
     */
    @PostMapping("/add")
    public ResponseResult add(@RequestBody User user) {
        try {
            int result = userService.register(user);
            if (result > 0) {
                return ResponseResult.success("用户新增成功");
            } else {
                return ResponseResult.error("用户新增失败");
            }
        } catch (Exception e) {
            return ResponseResult.error("用户新增失败: " + e.getMessage());
        }
    }

    /**
     * 修改用户密码
     * POST: /blog-api/v0.1/user/password/change
     */
    @PostMapping("/password/change")
    public ResponseResult changePassword(@RequestParam String userId, @RequestParam String newPassword) {
        try {
            int result = userService.changePassword(userId, newPassword);
            if (result > 0) {
                return ResponseResult.success("密码修改成功");
            } else {
                return ResponseResult.error("密码修改失败");
            }
        } catch (Exception e) {
            return ResponseResult.error("修改密码失败: " + e.getMessage());
        }
    }
}